<template>
	<div class="home" ref="home">
		<vue-esign
		  id='canvas'
		  ref="esign"
		  :width='pageWidth'
		  :height="pageHeight"
		  style="border: 1px dashed #c2c1c1;"
		  :isCrop="data.isCrop"
		  :lineWidth="data.lineWidth"
		  :isClearBgColor="false"
		  :lineColor="data.lineColor"/>
			<div class="operation">
				<van-button type="default" @click="onClear">清除</van-button>
				<van-button type="primary" @click="handleGenerate" plain>确认</van-button>
			</div>
			<div class="remark">请 签 名</div>
	</div>
</template>

<script setup lang="ts">
import { showComponent } from '@/utils/directiveComponents.ts'
const data:Ref<any> = ref({
	lineWidth: 8,
    lineColor: '#000000',
    resultImg: '',
    isCrop: false
})
const url:Ref<string> = ref('')
const esign:Ref<InstanceType<any>> = ref(null)
const pageWidth = window.innerWidth
const pageHeight = window.innerHeight

// 获取base64
const handleGenerate = () => {
	esign.value.generate().then((res:string) => {
		rotateBase64Image(res)
	}).catch((_:string) => {
		showComponent('ShowTost', '您还没有签名，请先签字!')
	})
}
let num = 0
// 清空
const onClear = () => {
	esign.value.reset();
	showComponent('ShowTost', {
		value:'清除成功',
		num:num++
	})
}
// 旋转base64图片
const rotateBase64Image = (base64Image:string) => {
	const img = new Image();
	img.onload = () => {
        let canvas = document.createElement('canvas');
        const ctx:any = canvas.getContext('2d');
        canvas.width = img.height;
        canvas.height = img.width;
        ctx.translate(canvas.width / 2, canvas.height / 2)
        ctx.rotate(-90 * Math.PI / 180);
        ctx.translate(-img.width / 2, -img.height / 2)
        ctx.drawImage(img, 0, 0, img.width, img.height)
        const newDataUrl = canvas.toDataURL('image/png')
		url.value = newDataUrl
		console.log(newDataUrl);
		
	};
	img.src = base64Image;
	return img
}
</script>


<style lang="scss" scoped>
.home{
	display: flex;
	height: 100%;
	#canvas{
		position: fixed;
		left: 0;
		top: 0;
		z-index: 801;
		border:none !important;
	}
	.operation{
		position: fixed;
		z-index: 802;
		transform: rotate(90deg);
		transform-origin:0 0;
		left: 60px;
		top: 42%;
	}
	.remark{
		position: fixed;
		z-index: 800;
		width: v-bind("pageHeight+'px'");
		height: v-bind("pageWidth+'px'");
		background-color: rgb(248, 248, 248);
		transform:translateX(-50%) translateY(-50%) rotate(90deg);
		left: 50%;
		top: 50%;
		font-size: 14px;
		pointer-events: none;
		color: #999;
		border: 3px dashed #c2c1c1;
		border-radius: 20px;
		text-align: center;
		line-height: v-bind("pageWidth+'px'");
	}
}

</style>